package com.example.demo.controller;

import com.example.demo.pojo.dbRole;
import com.example.demo.pojo.dbUser;
import com.example.demo.service.AdminService;
import com.example.demo.service.UserService;
import com.example.demo.vo.Result;
import com.example.demo.vo.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;


    @GetMapping("/show")
    public Result SelectAll(HttpServletRequest request){
        //判断是否有权限进入管理系统
        HttpSession session=request.getSession();
        Object admin = session.getAttribute("admin_name");
        if (admin!=null)
            return Result.success("登陆成功",admin);
        return Result.fail("请登录");
    }

    @GetMapping("/logout")
    public Result a(HttpServletRequest request){
        HttpSession session = request.getSession();
        Enumeration em = session.getAttributeNames();
        while(em.hasMoreElements()){
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return Result.success();
    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/selectUserAll")
    public Result selectUserAll(Integer ID){
        List<UserDetail> list = adminService.selectByUserAll(ID);
        return Result.success("成功",list);
    }



    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/deleteUserById/{id}")
    public Result deleteUserById(@PathVariable Integer id){
        int i=adminService.deleteUserById(id);
        if (i==1)
            return Result.success();
        return Result.fail("错误");
    }

    /**
     * 新增
     * @param userDetail
     * @return
     */
    @GetMapping("/add")
    public Result add(UserDetail userDetail){
        System.out.println(userDetail);
        Result result=adminService.add(userDetail);
        System.out.println(result);
        return result;
    }

    /**
     * 修改
     * @param userDetail
     * @return
     */
    @GetMapping("/update")
    public Result update(UserDetail userDetail){
        System.out.println(userDetail);
        Result result=adminService.update(userDetail);
        System.out.println(result);
        return result;
    }
}
